package com.krt.webapp.until;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.IntentFilter;
import android.telephony.gsm.SmsManager;
import android.widget.Toast;


@SuppressWarnings("deprecation")
public class SendMsg {
	
	private Context context;
	
	public SendMsg(Context context){
		this.context = context;
	}
	
		public void sendSMS(String phoneNo, String sMS) throws Exception
		{
			SmsManager sms = SmsManager.getDefault();
			
			String SENT_SMS_ACTION = "SENT_SMS_ACTION";
			String DELIVERED_SMS_ACTION = "DELIVERED_SMS_ACTION";
			
			Intent sent = new Intent(SENT_SMS_ACTION);
			PendingIntent sentPI = PendingIntent.getBroadcast(context, 0, sent, 0);
			
			Intent delivered = new Intent(DELIVERED_SMS_ACTION);
			PendingIntent deliveredPI = PendingIntent.getBroadcast(context, 0, delivered, 0);
			
			context.registerReceiver(new BroadcastReceiver() {
				
				@Override
				public void onReceive(Context context, Intent intent) 
				{
					switch (getResultCode()) 
					{
					case Activity.RESULT_OK:
						Toast.makeText(((ContextWrapper) context).getBaseContext(), "短信发送成功！", Toast.LENGTH_SHORT).show();
						break;

					case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
						Toast.makeText(((ContextWrapper) context).getBaseContext(), "短信发送失败！", Toast.LENGTH_SHORT).show();
						break;
						
					case SmsManager.RESULT_ERROR_NULL_PDU:
						Toast.makeText(((ContextWrapper) context).getBaseContext(), "短信发送失败！", Toast.LENGTH_SHORT).show();
						break;
					}
				}
			}, new IntentFilter(SENT_SMS_ACTION));
			
			context.registerReceiver(new BroadcastReceiver() {
				
				@Override
				public void onReceive(Context context, Intent intent) 
				{
					// TODO 自动生成的方法存根
					Toast.makeText(((ContextWrapper) context).getBaseContext(), "对方已成功接收短信！", Toast.LENGTH_SHORT).show();
					context.unregisterReceiver(this);
				}
			}, new IntentFilter(DELIVERED_SMS_ACTION));
			
			
				sms.sendTextMessage(phoneNo, null, sMS, sentPI, deliveredPI);
			
		}
}
